(function() {
	if((sessionStorage.chatBoxContent && sessionStorage.chatBoxContent == 1) || document.getElementById('chatBoxContent')) {
		//return;
	}
	//初始化array,添加indexOf方法
	if(!window.Array.indexOf) {
		window.Array.prototype.indexOf = function(obj) {
			for(var i = 0; i < this.length; i++) {
				if(this[i] == obj) {
					return i;
				}
			}
			return -1;
		}
	} else {
		window.Array.prototype.remove = function(val) {
			if(this.indexOf(val) > -1) {
				this.splice(index, 1);
			}
		};
	}
	/**************************************业务部分START****************************************/
	window.emojjiSrc='../img/smiles/';
	var chatHtml = '<div id="chatBoxContent">' +
		'<div class="chatbar">' +
		'<div class="messageTit"><label class="chatLogo0"></label>仁建讯通</div>' +
		'<div class="messageNow"><span class="shakeing-shake"><label class="chatLogo1"></label>您有新消息未读</span></div>' +
		'</div>' +
		'<div class="chatbox">' +

		'<div class="chatslectbar">' +
		'<div class="myhead"></div>' +
		'<div class="myname"></div>' +
		'<div class="chattabs">' +
		'<img class="chatbartab on" src="img/chat.png" />' +
		'<img class="chatbartab notice" src="img/group.png" />' +
		'</div>' +
		'</div>' +

		'<div class="chatclass">' +
		'<div class="onechat">' +
		'<div class="contact">' +
		'<div class="contactsearch">' +
		'<input type="" name="" id="contactsearch" value="" placeholder="查找联系人" />' +
		'<img id="search" src="img/search.png" />' +
		'</div>' +
		'<ul id="contactlist" class="contactlist">' +
		'<li>' +
		'<div class="organization" data-orgid="0"></div>' +
		'</li>' +
		'</ul>' +
		'</div>' +

		'<div class="chatwindow">' +
		'<div class="chattitle">' +
		'<p id="chattitlecon"></p>' +
		'<img class="close" id="close-chat" src="img/close.png" />' +
		'</div>' +
		'<div class="chat" id="chatList"></div>' +
		'<div class="chatinput" style="position:relative;">' +
		
		'<div class="callButtonBox">'+
			'<div class="videoButton" title="视频"></div>'+
			'<div class="voiceButton" title="语音"></div>'+
		'</div>'+
		
		'<ul class="smile-ul">'+
			'<li data-key="[):]" class="webim-emoji-item"><img data-smile="[):]" src="'+emojjiSrc+'ee_1.png"></li>'+
			'<li data-key="[:D]" class="webim-emoji-item"><img data-smile="[:D]" src="'+emojjiSrc+'ee_2.png"></li>'+
 			'<li data-key="[;)]" class="webim-emoji-item"><img data-smile="[;)]" src="'+emojjiSrc+'ee_3.png"></li>'+
 			'<li data-key="[:-o]" class="webim-emoji-item"><img data-smile="[:-o]" src="'+emojjiSrc+'ee_4.png"></li>'+
 			'<li data-key="[:p]" class="webim-emoji-item"><img data-smile="[:p]" src="'+emojjiSrc+'ee_5.png"></li>'+
 			'<li data-key="[(H)]" class="webim-emoji-item"><img data-smile="[(H)]" src="'+emojjiSrc+'ee_6.png"></li>'+
 			'<li data-key="[:@]" class="webim-emoji-item"><img data-smile="[:@]" src="'+emojjiSrc+'ee_7.png"></li>'+
 			'<li data-key="[:s]" class="webim-emoji-item"><img data-smile="[:s]" src="'+emojjiSrc+'ee_8.png"></li>'+
 			'<li data-key="[:$]" class="webim-emoji-item"><img data-smile="[:$]" src="'+emojjiSrc+'ee_9.png"></li>'+
 			'<li data-key="[:(]" class="webim-emoji-item"><img data-smile="[:(]" src="'+emojjiSrc+'ee_10.png"></li>'+
 			"<li data-key=\"[:'(]\" class=\"webim-emoji-item\"><img data-smile=\"[:'(]\" src=\""+emojjiSrc+"ee_11.png\"></li>"+
 			"<li data-key=\"[:|]\" class=\"webim-emoji-item\"><img data-smile=\"[:|]\" src=\""+emojjiSrc+"/ee_12.png\"></li>"+
 			'<li data-key="[(a)]" class="webim-emoji-item"><img data-smile="[(a)]" src="'+emojjiSrc+'ee_13.png"></li>'+
 			'<li data-key="[8o|]" class="webim-emoji-item"><img data-smile="[8o|]" src="'+emojjiSrc+'ee_14.png"></li>'+
 			'<li data-key="[8-|]" class="webim-emoji-item"><img data-smile="[8-|]" src="'+emojjiSrc+'ee_15.png"></li>'+
 			'<li data-key="[+o(]" class="webim-emoji-item"><img data-smile="[+o(]" src="'+emojjiSrc+'ee_16.png"></li>'+
 			'<li data-key="[|-)]" class="webim-emoji-item"><img data-smile="[|-)]" src="'+emojjiSrc+'ee_18.png"></li>'+
 			'<li data-key="[*-)]" class="webim-emoji-item"><img data-smile="[*-)]" src="'+emojjiSrc+'ee_19.png"></li>'+
 			'<li data-key="[:-#]" class="webim-emoji-item"><img data-smile="[:-#]" src="'+emojjiSrc+'ee_20.png"></li>'+
 			'<li data-key="[:-*]" class="webim-emoji-item"><img data-smile="[:-*]" src="'+emojjiSrc+'ee_21.png"></li>'+
 			'<li data-key="[^o)]" class="webim-emoji-item"><img data-smile="[^o)]" src="'+emojjiSrc+'ee_22.png"></li>'+
 			'<li data-key="[8-)]" class="webim-emoji-item"><img data-smile="[8-)]" src="'+emojjiSrc+'ee_23.png"></li>'+
 			'<li data-key="[(|)]" class="webim-emoji-item"><img data-smile="[(|)]" src="'+emojjiSrc+'ee_24.png"></li>'+
 			'<li data-key="[(u)]" class="webim-emoji-item"><img data-smile="[(u)]" src="'+emojjiSrc+'ee_25.png"></li>'+
 			'<li data-key="[(S)]" class="webim-emoji-item"><img data-smile="[(S)]" src="'+emojjiSrc+'ee_26.png"></li>'+
 			'<li data-key="[(*)]" class="webim-emoji-item"><img data-smile="[(*)]" src="'+emojjiSrc+'ee_27.png"></li>'+
 			'<li data-key="[(#)]" class="webim-emoji-item"><img data-smile="[(#)]" src="'+emojjiSrc+'ee_28.png"></li>'+
 			'<li data-key="[(R)]" class="webim-emoji-item"><img data-smile="[(R)]" src="'+emojjiSrc+'ee_29.png"></li>'+
 			'<li data-key="[({)]" class="webim-emoji-item"><img data-smile="[({)]" src="'+emojjiSrc+'ee_30.png"></li>'+
 			'<li data-key="[(})]" class="webim-emoji-item"><img data-smile="[(})]" src="'+emojjiSrc+'ee_31.png"></li>'+
 			'<li data-key="[(k)]" class="webim-emoji-item"><img data-smile="[(k)]" src="'+emojjiSrc+'ee_32.png"></li>'+
 			'<li data-key="[(F)]" class="webim-emoji-item"><img data-smile="[(F)]" src="'+emojjiSrc+'ee_33.png"></li>'+
 			'<li data-key="[(W)]" class="webim-emoji-item"><img data-smile="[(W)]" src="'+emojjiSrc+'ee_34.png"></li>'+
 			'<li data-key="[(D)]" class="webim-emoji-item"><img data-smile="[(D)]" src="'+emojjiSrc+'ee_35.png"></li>'+
 		'</ul>'+
		
		'<textarea id="inputcon" style="height:45px;" maxlength="200"></textarea>'+

		'<pre id="inputconPre" contenteditable="true" style="height:45px;" maxlength="200"></pre>'+

		'<label for="chosepic" id="fileLbel" class="emojiicon emoji0" title="图片">'+
		
		
		'<input type="file" class="chosepic" id="chosepic" accept="image/png,image/x-png,image/gif,image/x-ms-bmp, image/bmp,image/jpg,image/jpeg"/></label>'+
		'<div class="emojiicon emoji1" title="表情"></div>'+

		'<label for="chosedoc" id="fileLbel1" class="emojiicon emoji2" title="文件">'+
		'<input type="file" class="chosepic" id="chosedoc" accept="'+
							'image/jpg,image/gif,image/gif,image/png,image/bmp,aplication/zip,'+
							'text/plain,application/msword,application/pdf,audio/mp4,video/mp4"/></label>'+

		'<label for="choseVideo" id="fileLbel2" class="emojiicon emoji3" title="视频">'+
		'<input type="file" class="chosepic" accept="audio/*," id="choseVideo"/></label>'+
		'<input id="sentbtn" type="button" value="发送" />' +
		'</div>' +
		'</div>' +
		'</div>' +

		'<div>' +
		'<img class="close" id="close-chat1" src="img/close.png" />' +
		'<div class="contact" style="height: 400px;">' +
		'<div style="padding: 14px;text-align: center;">消息时间</div>' +
		'<ul id="noticeList" class="contactlist">' +
		'</ul>' +
		'</div>' +
		'</div>' +

		'</div>' +
		'<div class="groupMess">' +
		'<img class="close" id="close-chat2" src="img/close.png" />' +
		'<p style="text-align: center;">管理员消息</p>' +
		'<p id="groupMessCont" style="color: #A0A0A0;"></p>' +
		'</div>' +

		'</div>' +
		'</div>';
	$('body').append(chatHtml);

	window.chatUtils = {
		//本人信息
		userInfo: {
			name: '',
			nickname: '',
			password: '123456'
		},
		noticeList: [],
		//好友列表
		friends: [],
		localStorageList: localStorage.getItem('localStorageList') ? JSON.parse(localStorage.getItem('localStorageList')) : null,
		//通知列表信息
		notices: [],
		windowStatue: false,
		smileList:{
	        "[):]": "ee_1.png",
			"[:D]": "ee_2.png",
			"[;)]": "ee_3.png",
			"[:-o]": "ee_4.png",
			"[:p]": "ee_5.png",
			"[(H)]": "ee_6.png",
			"[:@]": "ee_7.png",
			"[:s]": "ee_8.png",
			"[:$]": "ee_9.png",
			"[:(]": "ee_10.png",
			"[:'(]": "ee_11.png",
			"[:|]": "ee_12.png",
			"[(a)]": "ee_13.png",
			"[8o|]": "ee_14.png",
			"[8-|]": "ee_15.png",
			"[+o(]": "ee_16.png",
			"[|-)]": "ee_18.png",
			"[*-)]": "ee_19.png",
			"[:-#]": "ee_20.png",
			"[:-*]": "ee_21.png",
			"[^o)]": "ee_22.png",
			"[8-)]": "ee_23.png",
			"[(|)]": "ee_24.png",
			"[(u)]": "ee_25.png",
			"[(S)]": "ee_26.png",
			"[(*)]": "ee_27.png",
			"[(#)]": "ee_28.png",
			"[(R)]": "ee_29.png",
			"[({)]": "ee_30.png",
			"[(})]": "ee_31.png",
			"[(k)]": "ee_32.png",
			"[(F)]": "ee_33.png",
			"[(W)]": "ee_34.png",
			"[(D)]": "ee_35.png"
	    },
	    chatshow:-1,
		resetWindowStatue: function() {
			if(chatUtils.resetWindowStatue) {
				$('.messageTit').show();
				$('.messageNow').hide();
			} else {
				$('.messageTit').hide();
				$('.messageNow').show();
			}
		},
		//登录功能
		loginIM: function(username, loginTime) {
			if(username && jQuery.trim(username) != '') {
				var loginTime = loginTime ? loginTime : 0;
				var options = {
					apiUrl: WebIM.config.apiURL,
					user: username,
					pwd: '123456',
					appKey: WebIM.config.appkey,
					success: function(data) {
						//登录成功
						var user = data.user;
						chatUtils.userInfo.name = user.username;
					},
					error: function(data) {
						//登录失败
						if(loginTime < 4) {
							chatUtils.loginIM(username, ++loginTime)
						} else {
							chatUtils.registe(username, 1);
						}
					}
				};
				conn.open(options);
			}
		},
		/*注册接口 START*/
		registe: function(username, regiTime) {
			if(username && jQuery.trim(username) != '') {
				conn.registerUser({
					username: username,
					password: '123456',
					nickname: 'nickname',
					appKey: WebIM.config.appkey,
					success: function() {
						chatUtils.loginIM(username);
					},
					error: function() {
						if(regiTime == undefined || regiTime < 3) {
							regiTime ? regiTime++ : 1;
							chatUtils.registe(username, regiTime);
						} else {
							alert('注册失败');
						}
					},
					apiUrl: WebIM.config.apiURL
				});
			} else {
				console.log('用户名为空');
			}
		},
		//登出功能
		loginOut: function() {
			conn.close();
		},
		//获取组织架构并持久化
		getOrganizationList: function(organizationId) {
			$.ajax({
				type: "GET",
				url: "/huanxin/inquireOrganizationList",
				data: {},
				dataType: "json",
				success: function(data) {
					var organs = data.datas;
					var isArray=Object.prototype.toString.call(organs) === '[object Array]'
					organs=isArray?organs:[];
					organs.sort(function(a, b) {
						return(a.organizationId - b.organizationId);
					});
					chatUtils.newOrgans = organs;
					var promisList = new Array(organs.length);
					for(var i = 0; i < promisList.length; i++) {
						promisList[i] = new Promise(function(resolve, reject) {
							var j = i;
							$.ajax({
								type: "GET",
								url: "/huanxin/inquireEmployeeList?pageSize=500&pageIndex=1",
								data: {
									orgId: organs[i].organizationId
								},
								dataType: "json",
								success: function(data) {
									var myList = data.datas;
									var isArray=Object.prototype.toString.call(myList) === '[object Array]'
									myList=isArray?myList:[];
									myList.sort(function(a, b) {
										return(a.employeeId - b.employeeId);
									});
									chatUtils.newOrgans[j].employeeList = myList;
									j = null;
									resolve();
								}
							});
						});
					}
					Promise.all(promisList).then(function(e) {
						var list = chatUtils.newOrgans instanceof Array ? chatUtils.newOrgans : [];
						var myList = [];
						var employeeList = null;
						for(var i = 0; i < list.length; i++) {
							employeeList = list[i].employeeList;
							for(var j = 0; j < employeeList.length; j++) {
								myList.push(employeeList[j]);
							}
						}
						//获取老数据
						var oldList = $.trim(localStorage.getItem('localStorageList'));
						//获取新数据
						var newList = $.trim(JSON.stringify(list));
						if(oldList.length < newList.length) {
							//更新dom，保存新数据
							chatUtils.createTree(list);
							//保存全体架构
							localStorage.setItem('localStorageList', JSON.stringify(list));
						}
					});
				}
			});
		},
		//search输入框监听匹配好友
		searchname: function() {
			var name = $.trim($("#contactsearch").val());
			if(name == "") {
				$("#contactlist .one-item").show();
			} else {
				$("#contactlist .one-item").each(
					function() {
						var parentEle = $(this).parent();
						var sectionIsOn = parentEle.css("display") == 'none';
						if($(this).children('.employee').text().indexOf(name) >= 0) {
							sectionIsOn ? parentEle.prev('.sectionname').trigger("click") : '';
							$(this).show();
						} else {
							$(this).hide();
						}
					}
				);
			}
		},
		//手动弹出与某人的私聊
		chatWithSbByName:function(mobile){
			var mobi = $.trim(mobile);
			var isHide=$('.chatbox').is(":hidden");
			if(mobi && mobi != ""){
				$("#contactlist .one-item").each(
					function() {
						var parentEle = $(this).parent();
						var sectionIsOn = parentEle.css("display")=='none';
						if($(this).children('.employee').data('mobile') == mobi) {
							isHide ? $('.chatbar').trigger('click') : '';
							sectionIsOn ? parentEle.prev('.sectionname').trigger("click") : '';
							$('.contselected').removeClass('contselected');
							$(this).addClass('contselected').trigger("click");
							$('#contactlist').animate({scrollTop:$(this).offset().top}, 'slow');
							return false;
						}
					}
				);
			}
		},
		//发送文本消息
		send: function(message, to) {
			if(to==chatUtils.userInfo.name){
				$('#chat'+to).append("<li>"+
										"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
										"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
									"</li>");
					return;
			}else{
				chatUtils.showMySend(message, to);
				var id = conn.getUniqueId(); // 生成本地消息id
				var msg = new WebIM.message('txt', id); // 创建文本消息
				msg.set({
					msg: message, // 消息内容
					to: to, // 接收消息对象（用户id）
					roomType: false,
					success: function(id, serverMsgId) {}
				});
				msg.body.chatType = 'singleChat';
				conn.send(msg.body);
				console.log('发送了： '+message);
			}
		},
		//发送后显示发送内容
		showMySend:function(message, to){
			if(to==chatUtils.userInfo.name){
				$('#chat'+to).append("<li>"+
										"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
										"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
									"</li>");
					return;
			}else{
				var emojiStr=WebIM.utils.parseEmoji(message);
				console.log(emojiStr);
				$('#chat'+to).append("<li><div class='speakManR'>我:</div><div class='myimg'></div><div class='myconpop'>" + 
					emojiStr + "</div><div class='clear'></div></li>");
				$('#inputcon').val('');
			}
		},
		//渲染组织架构
		createTree: function(organList) {
			var organList = organList ? organList : [];
			var html0 = '';
			var html1 = '';
			var employeeList = null;
			for(var i = 0; i < organList.length; i++) {
				html0 += '<li>' +
					'<div class="organization" data-orgid="' + organList[i].organizationId + '">' +
					'<div class="sectionname">' + organList[i].name + '<div class="rightIcon icon-close"></div>' +
					'<div class="noreadOut"></div></div>' +
					'<ul class="orgbox" id="orgbox' + organList[i].organizationId + '">';
				employeeList = organList[i].employeeList;
				for(var j = 0; j < employeeList.length; j++) {
					chatUtils.friends.push(employeeList[j].mobile);
					html0 += '<li class="one-item">' +
						'<div class="head-logo"></div>' +
						'<div class="employee" data-state="' + employeeList[j].state +
						'"  data-mobile="' + employeeList[j].mobile + '" data-employeeId="' + employeeList[j].employeeId + '">' + employeeList[j].name + '</div>' +
						'<div class="noread" id="noread' + employeeList[j].mobile + '">0</div>' +
						'</li>';
					html1 += '<div data-name="' + employeeList[j].mobile + '" class="chatcon">' +
						'<ul id="chat' + employeeList[j].mobile + '" class = "chatconlist" ></ul>' +
						'</div>';
				}
				html0 += '</ul>' +
					'</div>' +
					'</li>';
			}
			$("#contactlist").html(html0);
			$('#chatList').html(html1);
			chatUtils.init();
		},
		//处理接收群发消息
		showNotice: function(data, comefrom) {
			$('#groupMessCont').text(data)
			$('.groupMess').show();
			var date = new Date();
			var month = date.getMonth() + 1;
			var day = date.getDate();
			var hour = date.getHours();
			var minute = date.getMinutes();
			var second = date.getSeconds();
			var time = month + '月' + day + '日 ' + hour + ':' + minute + ':' + second;
			var noticeItem = {
				time: time,
				content: data
			};
			$('#noticeList').prepend('<li>' + noticeItem.time + '</li>');
			chatUtils.noticeList.splice(0, 0, noticeItem);
			chatUtils.initPage2();
		},
		//显示对方发送的文字信息noread
		showTextMessage: function(data, comefrom) {
			if(!document.getElementById('chatAudio')) {
				$('<audio style="filter:alpha(opacity=50);-moz-opacity:0;opacity:0;" id="chatAudio">'+
				'<source src="./img/notify.ogg" type="audio/ogg"></audio>').appendTo('body');
			}
			$('#chatAudio')[0].play();
			comefrom = $.trim(comefrom);
			if(comefrom == 'Manager' || comefrom == 'manager' || comefrom == 'admin' || comefrom == 'Admin') {
				//显示群发消息
				chatUtils.showNotice(data, comefrom);
				return;
			}
			if(document.getElementById('chat' + comefrom) == undefined || document.getElementById('chat' + comefrom) == null) {
				chatUtils.delay(data, comefrom, 3);
			} else {
				chatUtils.doAddMessage(data, comefrom);
			}
			chatUtils.init();
		},
		//延迟加载聊天方法noread
		delay: function(data, comefrom, num) {
			if(num > 0) {
				if(document.getElementById('chat' + comefrom) == undefined || document.getElementById('chat' + comefrom) == null) {
					setTimeout(function() {
						chatUtils.delay(data, comefrom, --num);
					}, 300);
				} else {
					chatUtils.doAddMessage(data, comefrom);
				}
			} else {
				console.log('信息获取异常');
			}
		},
		sendImgOrNot:function(msg){
			var file  = document.querySelector('#chosepic').files[0];
			var reader = new FileReader();
				reader.onloadend = function () {
				var bigImgBox=$('<div class="bigImgBox">'+
									'<div class="" style="position: relative;width: 100%;height: 100%;" onmousewheel="return bigerimg(this)">'+
										'<img src="'+reader.result+'"/>'+
									'</div>'+
									'<div class="img-choice">'+
										'<span>确认发送此图?</span>'+
										'<div style="padding:15px;">'+
											'<div class="choice-button choice-button-l">是</div>'+
											'<div class="choice-button choice-button-r">否</div>'+
										'</div>'+	
										'<div style="clear:both;"><div>'+
									'</div>'+
								'</div>');
				$('body').append(bigImgBox);
				$('.bigImgBox').on('click','.choice-button-l',function(){
					$('.bigImgBox').remove();
					conn.send(msg);
				});
				$('.bigImgBox').on('click','.choice-button-r',function(){
					$('.bigImgBox').remove();
				});
				$('#chosepic').remove();
			    var newFileDom='<input type="file" class="chosepic" id="chosepic" accept="image/png,image/x-png,image/gif,image/x-ms-bmp, image/bmp,image/jpg,image/jpeg"/>';
			    $('#fileLbel').append(newFileDom);
				
				$('.bigImgBox').dblclick(function(){
					$(this).remove();
				});
			}
			if (file) {
				reader.readAsDataURL(file);
			}
		},
		sendDocOrNot:function(msg){
			var file  = document.querySelector('#chosedoc').files[0];
			var fileTypeNum=file.name.lastIndexOf('.');
			var fileType=file.name.substring(fileTypeNum+1,file.name.length);
			var fileName=file.name.substring(0,fileTypeNum);
			fileName=fileName.length>7?fileName.substring(0,7):fileName;
			
			var fileSize = 0;
			var isIE = /msie/i.test(navigator.userAgent) && !window.opera;      
			if (isIE && !file) {
			    var filePath = file.value;      
			    var fileSystem = new ActiveXObject("Scripting.FileSystemObject");  
			    var file = fileSystem.GetFile (filePath);        
			    fileSize = file.Size;     
			}else {
			    fileSize = file.size;   
			} 
			fileSize=(Math.round(fileSize/1024*100)/100)/1024; //单位为KB
			if(fileSize>20){
				alert("文件大小超过20M!");
				return false;
			}
			var bigImgBox=$('<div class="bigImgBox">'+
								'<div class="img-choice" style="height:auto;max-height:95px;">'+
									'<span>确认发送&nbsp;<span style="color:gray;">'+fileName+'.'+fileType+'</span>&nbsp;?</span>'+
									'<div style="padding:15px;">'+
										'<div class="choice-button choice-button-l">是</div>'+
										'<div class="choice-button choice-button-r">否</div>'+
									'</div>'+	
									'<div style="clear:both;"><div>'+
								'</div>'+
							'</div>');
			$('body').append(bigImgBox);
			$('.bigImgBox').on('click','.choice-button-l',function(){
				$('.bigImgBox').remove();
				conn.send(msg);
			});
			$('.bigImgBox').on('click','.choice-button-r',function(){
				$('.bigImgBox').remove();
			});
			$('#chosedoc').remove();
		    var newFileDom='<input type="file" class="chosepic" id="chosedoc" accept="'+
					    	'image/jpg,image/gif,image/gif,image/png,image/bmp,aplication/zip,'+
					    	'text/plain,application/msword,application/pdf,audio/mp4,video/mp4"/>';
		    $('#fileLbel1').append(newFileDom);
			
			$('.bigImgBox').dblclick(function(){
				$(this).remove();
			});
		},
		
		sendVideoOrNot:function(msg){
			var file  = document.querySelector('#choseVideo').files[0];
			var fileTypeNum=file.name.lastIndexOf('.');
			var fileType=file.name.substring(fileTypeNum+1,file.name.length);
			var fileName=file.name.substring(0,fileTypeNum);
			fileName=fileName.length>7?fileName.substring(0,7):fileName;
			
			var fileSize = 0;
			var isIE = /msie/i.test(navigator.userAgent) && !window.opera;      
			if (isIE && !file) {
			    var filePath = file.value;      
			    var fileSystem = new ActiveXObject("Scripting.FileSystemObject");  
			    var file = fileSystem.GetFile (filePath);        
			    fileSize = file.Size;     
			}else {
			    fileSize = file.size;   
			} 
			fileSize=(Math.round(fileSize/1024*100)/100)/1024; //单位为KB
			if(fileSize>20){
				alert("文件大小超过20M!");
				return false;
			}
			
			console.log(msg);
			
			var bigImgBox=$('<div class="bigImgBox">'+
								'<div class="img-choice" style="height:auto;max-height:95px;">'+
									'<span>确认发送&nbsp;<span style="color:gray;">'+fileName+'.'+fileType+'</span>&nbsp;?</span>'+
									'<div style="padding:15px;">'+
										'<div class="choice-button choice-button-l">是</div>'+
										'<div class="choice-button choice-button-r">否</div>'+
									'</div>'+	
									'<div style="clear:both;"><div>'+
								'</div>'+
							'</div>');
			$('body').append(bigImgBox);
			$('.bigImgBox').on('click','.choice-button-l',function(){
				$('.bigImgBox').remove();
				conn.send(msg);
				console.log(msg);
			});
			$('.bigImgBox').on('click','.choice-button-r',function(){
				$('.bigImgBox').remove();
			});
			$('#choseVideo').remove();
		    var newFileDom='<input type="file" class="chosepic" accept="audio/*," id="choseVideo"/>';
		    
		    $('#fileLbel2').append(newFileDom);
			
			$('.bigImgBox').dblclick(function(){
				$(this).remove();
			});
		},
		
		//将接收到的新聊天信息添加到对应聊天框
		doAddMessage: function(data, comefrom) {
			comefrom = comefrom ? comefrom : '';
			if(chatUtils.friends.indexOf(comefrom) >= 0) {
				var num = parseInt($.trim($('#noread' + comefrom).text()));
				var orgbox = $('#noread' + comefrom).parent().parent();
				var department = orgbox.prev().find('.noreadOut');
				if($('.chatshow') && ($('.chatshow').data('name') == comefrom)) {
					$('#noread' + comefrom).text('0').removeClass('showStyle');
					department.length > 0 ? department.hide() : '';
				} else {
					department.show();
					$('#noread' + comefrom).text(++num).addClass('showStyle');
				}
				var nameText = $('#noread' + comefrom).prev().text();
				$('#chat' + comefrom).append("<li><div class='speakManL'>"+ nameText + ":</div><div class='myimgL'></div><div class='myconpopL'>" + data +
					"</div><div class='clear'></div></li>");
			}
			document.dispatchEvent(ev);
			chatUtils.init();
		},
		//初始化或重置
		init: function() {
			//点击tab页切换
			$(".one-item").each(function(num) {
				var that = $(this);
				that.off("click").on('click', function() {
					$(".one-item").removeClass("contselected");
					that.addClass("contselected");
					$(".chat>div").eq(num).show().addClass("chatshow").siblings().hide().removeClass("chatshow");
					setTimeout(function() {
						var comefrom = chatUtils.friends[num];
						that.children('.noread').text('0').removeClass('showStyle');
						var hasNoread = $('#noread' + comefrom).parent().parent().find('.showStyle').size();
						var department = $('#noread' + comefrom).parent().parent().prev().find('.noreadOut');
						hasNoread <= 0 ? department.hide() : '';

					}, 800);
					var contactname1 = $.trim(that.children('.employee').html());
					$('#chattitlecon').html("与<span style='color:coral;'>   " + contactname1 + "   </span>聊天中");
				});
			});
			$(".sectionname").click(function() {
				$(this).next().toggle();
				var icon = $(this).find('.rightIcon');
				var hasClas = icon.hasClass('icon-close');
				hasClas ? icon.removeClass('icon-close').addClass('icon-open') : icon.removeClass('icon-open').addClass('icon-close');
			});
			var timeout=null;
			$(".chatconlist").off('DOMNodeInserted').on('DOMNodeInserted', function(e) {
				var list=$(".chatconlist");
				clearTimeout(timeout);
				timeout=setTimeout(function(){
					list.each(function(){
						this.scrollTop = this.scrollHeight;
					});
				},500);
			});
		},
		initPage2: function() {
			$('#noticeList > li').off('click').on('click', function() {
				$('#noticeList > li').removeClass('activeLi');
				$(this).addClass('activeLi');
				var num = $(this).index();
				$('#groupMessCont').text(chatUtils.noticeList[num].content);
				$('.groupMess').show();
			});
		}
	}
	/****************************************************系统入口*****************************************************/
	//获取即将用来登录的用户名
	WebIM.Emoji = {
	    path: emojjiSrc,  /*表情包路径*/
     	map: chatUtils.smileList
	};
	window.conn = new WebIM.connection({
		https: WebIM.config.https,
		url: WebIM.config.xmppURL,
		isAutoLogin: WebIM.config.isAutoLogin,
		isMultiLoginSessions: WebIM.config.isMultiLoginSessions
	});
	conn.listen({
		//登录后初始化
		onOpened: function(message) {
			//显示影藏表情框
			$('.emoji1').click(function(){
				$('.smile-ul').slideToggle("fast");
			});
			//添加表情到输入框
			$('.smile-ul > li').off('click').on('click',function(){
				$('#inputconPre').append($(this).find('img').clone());
				$('.smile-ul').hide();
			});
			//监听键盘按下事件
			$(document).off('paste,keyup').on('keyup',function(e){
				//退出键删除图片预览dom
				if(e.which===27){if($('.chatbox').is(":hidden")){return;}else{$('.bigImgBox').remove();}}
			}).on('paste','#inputconPre',function(e){
				ctrlImg(e.originalEvent);
			});
			var imgTimer=null;
			function ctrlImg(e) {
			    var cbd = e.clipboardData;
			    var ua = window.navigator.userAgent;
			    var toWho=$.trim($('.chatshow').data('name'));
			    // 如果是 Safari 直接 return
			    if (!(e.clipboardData && e.clipboardData.items)) {return;}
			    // Mac平台下Chrome49版本以下 复制Finder中的文件的Bug Hack掉
			    if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
			        cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
			        ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
			        return;
			    }
			    if(cbd.items[0].kind=="file"){
		    		for(var i = 0; i < cbd.items.length; i++) {
				        var item = cbd.items[i];
				        if(item.kind == "file"){
				            var blob = item.getAsFile();
				            if (blob.size === 0) {
				                return;
				            }
				            if($('.chatshow').size()>0&&(/^image\/\w+$/.test(item.type))){
				            	var blob = item.getAsFile();
				                var url = window.URL.createObjectURL(blob);
				                var id = conn.getUniqueId();             // 生成本地消息id
				                var msg = new WebIM.message('img', id);  // 创建图片消息
				                msg.set({
				                    apiUrl: WebIM.config.apiURL,
				                    file: {data: blob, url: url},
				                    to: toWho,							 // 接收消息对象
				                    roomType: false,
				                    chatType: 'singleChat',
				                    onFileUploadError: function (error) {},
				                    onFileUploadComplete: function (data) {
				                    	var list=data.entities;
				                    	for(var ji=0;ji<list.length;ji++){
				                    		var imgurl=data.uri+"/"+list[ji].uuid;
				                    		var message=' <a style="cursor: pointer;" class="openBigImg" data-url="'+imgurl+'"><img class="imgMes" src="'+imgurl+'"></a> ';
											chatUtils.showMySend(message,toWho);
				                    	}
				                    },
				                    success: function (id) {}
				                });
				                clearTimeout(imgTimer);
			    				imgTimer=setTimeout(function(){
			    					if(toWho==chatUtils.userInfo.name){
			    						$('#chat'+toWho).append("<li>"+
			    												"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
			    													"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
			    											"</li>");
			    							return;
			    					}
			    					chatUtils.sendImgOrNot(msg.body);
			    				},400);
				            }
				        }
				    }
			    }
			}
			//点击小图查显示大图
			$("#chatList").on("click",".openBigImg",function(e){
				var bigImgBox=$('<div class="bigImgBox" style="position: fixed;z-index:9999;width: 100%;height: 100%;top: 0;left: 0;background-color: rgba(0,0,0,0.3);overflow: hidden;">'+
									'<div style="position: relative;width: 100%;height: 100%;" onmousewheel="return bigerimg(this)">'+
										'<img src="'+$(this).data('url')+'" style="position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;cursor:pointer;"/>'+
									'</div>'+
								'</div>');
				$('body').append(bigImgBox);
				$('.bigImgBox').dblclick(function(){
					$(this).remove();
				})
			});
			//发送图片文件
			$("body").on("change",'#chosepic',function(){
				var chatshow=$.trim($('.chatshow').data('name'));
				var imgFile=document.getElementById('chosepic');
	            var id = conn.getUniqueId();                   // 生成本地消息id
			    var msg = new WebIM.message('img', id);        // 创建图片消息
			    var file = WebIM.utils.getFileUrl(imgFile);    // 将图片转化为二进制文件
			    var allowType = {
			        'jpg': true,
			        'gif': true,
			        'png': true,
			        'bmp': true
			    };
			    if (file.filetype.toLowerCase() in allowType) {
			        var option = {
			            apiUrl: WebIM.config.apiURL,
			            file: file,
			            to: chatshow,                         // 接收消息对象
			            roomType: false,
			            chatType: 'singleChat',
			            onFileUploadError: function (data) {      // 消息上传失败
			                console.log('onFileUploadError');
			            },
			            onFileUploadComplete: function (data) {   // 消息上传成功
			                var list=data.entities;
	                    	for(var ji=0;ji<list.length;ji++){
	                    		var imgurl=data.uri+"/"+list[ji].uuid;
	                    		var message=' <a style="cursor: pointer;" class="openBigImg" data-url="'+
	                    						imgurl+'"><img class="imgMes" src="'+imgurl+'"></a> ';
								chatUtils.showMySend(message,chatshow);
	                    	}
			            },
			            success: function (data) {// 消息发送成功
			                console.log('Success');
			            },
			            flashUpload: WebIM.flashUpload
			        };
			        msg.set(option);
			        if(chatshow==chatUtils.userInfo.name){
			        	$('#chat'+chatshow).append("<li>"+
					        							"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
					        								"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
					        						"</li>");
			        		return;
			        }
			        chatUtils.sendImgOrNot(msg.body);
			    }else{
			    	alert('请选择图片格式的文件');
			    }
			});
			
			//发送文件
			$("body").on("change",'#chosedoc',function(){
				var chatshow=$.trim($('.chatshow').data('name'));
			    var id = conn.getUniqueId();                   	// 生成本地消息id
			    var msg = new WebIM.message('file', id);        // 创建文件消息
			    var input = document.getElementById('chosedoc');  	// 选择文件的input
			    var file = WebIM.utils.getFileUrl(input);      	// 将文件转化为二进制文件
			    var allowType = {
			        'jpg': true,
			        'gif': true,
			        'png': true,
			        'bmp': true,
			        'zip': true,
			        'txt': true,
			        'doc': true,
			        'pdf': true,
			        'mp4': true,
			        'wmv': true,
			        'avi': true,
			        'rmvb':true,
			        'mkv':true
			    };
			    if (file.filetype.toLowerCase() in allowType) {
			        var option = {
			            apiUrl: WebIM.config.apiURL,
			            file: file,
			            to: chatshow,                       // 接收消息对象
			            roomType: false,
			            chatType: 'singleChat',
			            onFileUploadError: function () {      // 消息上传失败
			                console.log('onFileUploadError');
			            },
			            onFileUploadComplete: function (data) {   // 消息上传成功
			                $('#chat'+chatshow).append("<li>"+
						        							"<div style='width:50%;margin:0 auto;text-align:center;color:#CCCCCC;"+
						        								"padding:10px;font-size:13px;border-radius:6%;box-shadow:rgba(0, 0, 0, 0.298039) 0px 0px 6px 0px;'>"+
						        									"文件发送成功"+
						        								"</div>"+
						        						"</li>");
			            },
			            success: function () {                // 消息发送成功
			                console.log('Success');
			            },
			            flashUpload: WebIM.flashUpload
			        };
			        msg.set(option);
			        if(chatshow==chatUtils.userInfo.name){
			        	$('#chat'+chatshow).append("<li>"+
					        							"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
					        								"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
					        						"</li>");
			        		return;
			        }
			        chatUtils.sendDocOrNot(msg.body);
			    }else{
			    	alert('不支持此文件格式');
			    }
			    console.log(msg);
			});
			
			//发送音频
			$("body").on("change",'#choseVideo',function(){
				var chatshow=$.trim($('.chatshow').data('name'));
		     	var id = conn.getUniqueId();                   // 生成本地消息id
			    var msg = new WebIM.message('audio', id);      // 创建视频消息
			    var input = document.getElementById('choseVideo');  // 选择视频的input
			    var file = WebIM.utils.getFileUrl(input); 
			    var allowType = {
		          	'mp3': true,
			        'amr': true,
			        'wmv': true
			    };
			    if (file.filetype.toLowerCase() in allowType) {
			        var option = {
			            apiUrl: WebIM.config.apiURL,
			            file: file,
			            to: chatshow,                       // 接收消息对象
			            roomType: false,
			            chatType: 'singleChat',
			            onFileUploadError: function () {      // 消息上传失败
			                console.log('onFileUploadError');
			            },
			            onFileUploadComplete: function (data) {   // 消息上传成功
			                $('#chat'+chatshow).append("<li>"+
						        							"<div style='width:50%;margin:0 auto;text-align:center;color:#CCCCCC;"+
						        								"padding:10px;font-size:13px;border-radius:6%;box-shadow:rgba(0, 0, 0, 0.298039) 0px 0px 6px 0px;'>"+
						        									"音乐频发送成功"+
						        								"</div>"+
						        						"</li>");
			            },
			            success: function () {                // 消息发送成功
			                console.log('Success');
			            },
			            flashUpload: WebIM.flashUpload
			        };
			        msg.set(option);
			        if(chatshow==chatUtils.userInfo.name){
			        	$('#chat'+chatshow).append("<li>"+
					        							"<div style='width:50%;margin:0 auto;text-align:center;color:coral;background:#FBD6E7;"+
					        								"padding:10px;font-size:13px;border-radius:6%;'>您不能和自己聊天</div>"+
					        						"</li>");
			        		return;
			        }
			        chatUtils.sendVideoOrNot(msg.body);
			    }else{
			    	alert('请选择音频文件格式');
			    }
			    
			    console.log(msg);
			    
			});
			
			$("#close-chat2").off("click").on("click", function() {
				$(".groupMess").hide();
			});
			setTimeout(function() {
				var nickname=$('.one-item').eq(chatUtils.friends.indexOf(chatUtils.userInfo.name)).children('.employee').text();
				$('.myname').html($('.one-item').eq(chatUtils.friends.indexOf(chatUtils.userInfo.name)).children('.employee').text());
				chatUtils.userInfo.nickname=nickname;
			}, 1500);
			//监听发送信息框回车事件
			$("#inputconPre").keydown(function(e) {
				//回车发送消息
				var theEvent = window.event || e;
				var code = theEvent.keyCode || theEvent.which;
				if(code == 13) {
					document.getElementById('sentbtn').click();
				};
			}).on('input propertychange',function(){
				var that=$(this);
				deletePre(that);
				that.find('br').remove();
			});

			function deletePre(ele){
				var ele=ele;
				var children=ele.find('pre,div');
				 if(children.size()>0){
				 	children.each(function(){
				 		$(this).replaceWith($(this).html());
				 	});
				 	deletePre(ele);
				 }else{
				 	return ele;
				 }
			}

			/*大小框消失显现设置*/
			$(".chatbar").off("click").on("click", function() {
				chatUtils.windowStatue = true;
				$(this).hide().siblings().show();
				var chatshow=chatUtils.chatshow;
				if(chatshow>=0){
					$('.one-item').eq(chatshow).trigger('click');
				}
			});
			
			$("#close-chat,#close-chat1").off("click").on("click", function() {
				$('.contselected').removeClass('contselected');
				var chatshow=$('.chatshow');
				$('.chatcon').each(function(index){
					if(chatshow[0]==$(this)[0]){
						chatUtils.chatshow=index;
					}
				});
				$('.chatshow').removeClass('chatshow');
				
				chatUtils.windowStatue = false;
				$(".chatbox").hide().siblings().show();
				document.dispatchEvent(ev);
			});
			
			//绑定发送消息功能
			$("#sentbtn").off("click").on('click', function() {
				var newEle=$('#inputconPre').clone();
				newEle.find('img').each(function(){
					$(this).replaceWith($(this).data('smile'));
				});
				$('#inputcon').val(newEle.text().replace('\n',''));
				$('#inputconPre').html('');
				var myVal = $.trim($('#inputcon').val());
				if(myVal != '') {
					chatUtils.send(myVal, $.trim($('.chatshow').data('name')));
				}
				$('#inputcon').html('');
			});

			//搜索框输入事件绑定
			$('#contactsearch').off('input propertychange').on('input propertychange', function() {
				chatUtils.searchname();
			});
			//监听搜索框
			$('#search').click(function() {
				var val = $.trim($('#contactsearch') ? $('#contactsearch').val() : '');
				chatUtils.searchname();
			});
			//单聊,群聊,通知信息 tab切换
			$('.chattabs').children('img').click(function() {
				$(this).addClass("on").siblings().removeClass("on");
				var num = $(this).index();
				$(".chatclass>div").eq(num).show().siblings().hide();
			});
		},
		onClosed: function(message) {
			chatUtils.loginIM(chatUtils.userInfo.name,3);
		}, //连接关闭回调
		onTextMessage: function(message) {
			//console.log(message);
			chatUtils.showTextMessage(message.data, message.from);
		}, //收到文本消息
		onEmojiMessage: function(message) {
	        console.log(message);
	        var list = message.data;
	        var mess='';
	        for(var i = 0;i<list.length; i++){
	        	if(list[i].type=='emoji'){
	        		mess+=' <img src="'+list[i].data+'"/> ';
	        	}else{
	        		mess+=list[i].data;
	        	}
	        }
	        console.log(mess);
	        chatUtils.showTextMessage(mess, message.from);
		}, //收到表情消息
		onPictureMessage: function(message) {
			console.log(message);
			var imurl=$.trim(message.url);
			chatUtils.showTextMessage(' <a style="cursor: pointer;" class="openBigImg" data-url="'+imurl+'"><img class="imgMes" src="'+imurl+'"></a> ', message.from);
		}, //收到图片消息
		onCmdMessage: function(message) {}, //收到命令消息
		onAudioMessage: function(message) {
			console.log(message);
			var fileTypeNum=message.filename.lastIndexOf('.');
			var fileType=message.filename.substring(fileTypeNum+1,message.filename.length);
			var fileName=message.filename.substring(0,fileTypeNum);
			fileName=fileName.length>7?fileName.substring(0,7):fileName;
			chatUtils.showTextMessage(' <a style="cursor:pointer;text-decoration:none;color:#CCCCCC;" href="'+
											message.url+'">下载&nbsp;<div class="download1"></div>'+fileName+'.'+fileType+'</a> ', message.from);
		}, //收到音频消息
		onLocationMessage: function(message) {}, //收到位置消息
		onFileMessage: function(message) {
			console.log(message);
			var fileTypeNum=message.filename.lastIndexOf('.');
			var fileType=message.filename.substring(fileTypeNum+1,message.filename.length);
			var fileName=message.filename.substring(0,fileTypeNum);
			fileName=fileName.length>7?fileName.substring(0,7):fileName;
			chatUtils.showTextMessage(' <a style="cursor:pointer;text-decoration:none;color:#CCCCCC;" href="'+
											message.url+'">下载&nbsp;<div class="download0"></div>'+fileName+'.'+fileType+'</a> ', message.from);
		}, //收到文件消息
		onVideoMessage: function(message) {
			console.log(message);
			var fileTypeNum=message.filename.lastIndexOf('.');
			var fileType=message.filename.substring(fileTypeNum+1,message.filename.length);
			var fileName=message.filename.substring(0,fileTypeNum);
			fileName=fileName.length>7?fileName.substring(0,7):fileName;
			chatUtils.showTextMessage(' <a style="cursor:pointer;text-decoration:none;color:#CCCCCC;" href="'+
											message.url+'">下载&nbsp;<div class="download1"></div>'+fileName+'.'+fileType+'</a> ', message.from);
		}, //收到视频消息
		onPresence: function(e) {}, //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
		onRoster: function(message) {}, //处理好友申请
		onInviteMessage: function(message) {}, //处理群组邀请
		onOnline: function() {}, //本机网络连接成功
		onOffline: function() {}, //本机网络掉线
		onError: function(message) {}, //失败回调
		onBlacklistUpdate: function(list) {}
	});
	/*初始化实时通话*/
	window.rtcCall = new WebIM.WebRTC.Call({
	    connection: conn,
	    mediaStreamConstaints: {
	            audio: true,
	            video: true
	    },
	    listener: {
	        onAcceptCall: function (from, options) {
	        	console.log('链接成功!')
	            console.log('onAcceptCall::', 'from: ', from, 'options: ', options);
	        },
	        //通过streamType区分视频流和音频流，streamType: 'VOICE'(音频流)，'VIDEO'(视频流)
	        //获取远程连接
	        onGotRemoteStream: function (stream, streamType) {
	        	var eleBox=document.getElementById('videobox');
	        	if(eleBox==undefined||eleBox==null){
	        		if(streamType=='VIDEO'){
	        			$('body').append('<div id="videobox" style="width:100%;height:auto;">'+
							        	'<video id="video" autoplay controls="controls"></video>'+
							        	'<video id="localVideo" autoplay controls="controls"></video>'+
							        	'<div class="closeVideo"></div>'+
							    	'</div>');
	        		}else if(streamType=='VOICE'){
	        			$('body').append('<div id="videobox" class="phonecall">'+
							'<div style="position:relative;width:100%;height:100%;">'+
								'<video id="video" autoplay controls="controls" style="display:none;"></video>'+
					        	'<video id="localVideo" autoplay controls="controls" style="display:none;"></video>'+
					        	'<div class="closeVideo closeVoice"></div>'+
					        	'正在通话'+
					        	'<div class="smallPhone"></div>'+
							'</div>'+
				    	'</div>');
	        		}
	        	}else{
	        		$('#videobox').show();
	        	}
	            console.log('onGotRemoteStream::', 'stream: ', stream, 'streamType: ', streamType);
	            var video = document.getElementById('video');
	            video.srcObject = stream;
	        },
	        //获取本地连接
	        onGotLocalStream: function (stream, streamType) {
	        	var eleBox=document.getElementById('videobox');
	        	if(eleBox==undefined||eleBox==null){
	        		
	        		var fromWho='';
		        	$('.employee').each(function(){
		        		if($(this).data('mobile')==$.trim($('.chatshow').data('name'))){
	        				fromWho=$(this).text();
	        				console.log(fromWho);
		        		}
		        	});
	        		
	        		var callBox=$('<div class="callBox">'+
									'<div class="img-choice">'+
										'<span>正在呼叫 '+fromWho+'</span>'+
										'<div style="padding:15px;">'+
											'<div class="choice-button choice-button-call">挂断</div>'+
										'</div>'+	
										'<div style="clear:both;"><div>'+
									'</div>'+
								'</div>');
				
					$('body').append(callBox);
					$('.callBox').on('click','.choice-button-call',function(){
						rtcCall.endCall();
						$('.callBox').remove();
					});
	        		
	        		if(streamType=='VIDEO'){
	        			$('body').append('<div id="videobox" style="width:100%;height:auto;">'+
							        	'<video id="video" autoplay controls="controls"></video>'+
							        	'<video id="localVideo" autoplay controls="controls"></video>'+
							        	'<div class="closeVideo"></div>'+
							    	'</div>');
	        		}else if(streamType=='VOICE'){
	        			$('body').append('<div id="videobox" class="phonecall">'+
							'<div style="position:relative;width:100%;height:100%;">'+
								'<video id="video" autoplay controls="controls" style="display:none;"></video>'+
					        	'<video id="localVideo" autoplay controls="controls" style="display:none;"></video>'+
					        	'<div class="closeVideo closeVoice"></div>'+
					        	'正在通话'+
					        	'<div class="smallPhone"></div>'+
							'</div>'+
				    	'</div>');
	        		}
	        		
	        	}else{
	        		$('#videobox').show();
	        	}
	            console.log('onGotLocalStream::', 'stream:', stream, 'streamType: ', streamType);
	            var video = document.getElementById('localVideo');
	            video.srcObject = stream;
	        },
	        //正在呼叫
	        onRinging: function (caller) {
	        	var caller=caller?$.trim(caller):0;
	        	caller=caller.replace(/[^0-9]/ig,"");
	        	var fromWho='';
	        	$('.employee').each(function(){
	        		if($(this).data('mobile')==caller){
        				fromWho=$(this).text();
        				console.log(fromWho);
	        		}
	        	});
	        	var callBox=$('<div class="callBox">'+
									'<div class="img-choice">'+
										'<span>'+fromWho+'的来电</span>'+
										'<div style="padding:15px;">'+
											'<div class="choice-button choice-button-l">接听</div>'+
											'<div class="choice-button choice-button-r">挂断</div>'+
										'</div>'+	
										'<div style="clear:both;"><div>'+
									'</div>'+
								'</div>');
								
				$('body').append(callBox);
	        	$('.callBox').on('click','.choice-button-l',function(){
	        		rtcCall.acceptCall();
					$('.callBox').remove();
				});
				$('.callBox').on('click','.choice-button-r',function(){
					rtcCall.endCall();
					$('.callBox').remove();
				});
	            console.log('onRinging::', 'caller:', caller);
	        },
	        //挂断
	        onTermCall: function (reason) {
	            console.log('onTermCall::');
	            console.log('reason:', reason);
	            if(reason='busy'){
	            	alert('对方正忙,通话结束');
	            }
	        },
	        //状态改变
	        onIceConnectionStateChange: function (iceState) {
	        	if(iceState=='closed'){
	        		setTimeout(function(){
	        			$('#videobox,.callBox').remove();
	        			
	        		},1000)
	        		console.log('视屏关闭');
	        	}
	            console.log(iceState);
	        },
	        onError: function (e) {
	        	$('#videobox').remove();
	        	if(e.message&&e.message.indexOf('not online')>=0){
	        		alert('对方不在线');
	        	}else{
	        		alert('联接错误,请检查您的视频/音频设备');
	        	}
	            console.log(e);
	        }
	     }
	});
	
	$(document).on('click','.closeVideo',function(){
		rtcCall.endCall();
		setTimeout(function(){
			$('#videobox').remove();
		},500);
	}).on('click','.videoButton',function(){
		var to=$.trim($('.chatshow').data('name'));
		if(to!=undefined&&to!=''&&to!=chatUtils.userInfo.name){
	        rtcCall.caller = chatUtils.userInfo.name;
	        rtcCall.makeVideoCall(to);
		}
	}).on('click','.voiceButton',function(){
		var to=$.trim($('.chatshow').data('name'));
		if(to!=undefined&&to!=''&&to!=chatUtils.userInfo.name){
			rtcCall.caller = chatUtils.userInfo.name;
        	rtcCall.makeVoiceCall(to);
		}
	});
	
	$('#login').on('click', function() {
		chatUtils.loginIM(getUserName());
	});

	var oldList = $.trim(localStorage.getItem('localStorageList'));
	if(oldList && oldList != '') {
		//渲染tree
		chatUtils.createTree(JSON.parse(oldList));
	}
	
	window.crmLogin = function(username) {
		chatUtils.loginIM(username);
	}

	setTimeout(function() {
		chatUtils.getOrganizationList();
	}, 30);

	sessionStorage.chatBoxContent = 1;
	
	//自定义事件
	var ev = document.createEvent('HTMLEvents');
	ev.initEvent('listen', false, false);
　　document.addEventListener("listen", function(){
		var ele=$('.showStyle').size();
		var messageTit=$('.messageTit');
		var messageNow=$('.messageNow');
		if(ele>0){
			if(messageNow.is(':hidden')){
				messageTit.hide();
				messageNow.show();
			}
		}else{
			messageTit.show();
			messageNow.hide();
		}
	}, false);
	window.bigerimg=function(i){
		var zoom = parseInt(i.style.zoom,10)||100;
		zoom += event.wheelDelta / 12;
		if(zoom > 0 )
		i.style.zoom=zoom+'%';
		return false;
	};
	
}());